package com.cloudcc.mobile.view.schedule;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.bus.MenuToggleEventR;
import com.cloudcc.cloudframe.bus.MessageNumX;
import com.cloudcc.cloudframe.net.ErrorInfo;
import com.cloudcc.cloudframe.net.RequestListener;
import com.cloudcc.cloudframe.util.DateUtils;
import com.cloudcc.cloudframe.util.ListUtils;
import com.cloudcc.cloudframe.util.NearByUtil;
import com.cloudcc.cloudframe.util.StringUtils;
import com.cloudcc.mobile.ExtraConstant;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.ReceiverConstant;
import com.cloudcc.mobile.adapter.ScheduleListAdapter;
import com.cloudcc.mobile.adapter.ScheduleListAdapter.OnScheduleItemClickListener;
import com.cloudcc.mobile.dialog.CreatePopwindow;
import com.cloudcc.mobile.entity.schedule.ScheduleEntity;
import com.cloudcc.mobile.event.ScheduleEventList.ScheduleListEvent;
import com.cloudcc.mobile.event.isshow;
import com.cloudcc.mobile.manager.CacheManager;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.presenter.SchedulePresenter;
import com.cloudcc.mobile.util.PopuWindowUtils;
import com.cloudcc.mobile.util.SystemUtils;
import com.cloudcc.mobile.util.UrlTools;
import com.cloudcc.mobile.view.activity.BeauInfoActivity;
import com.cloudcc.mobile.view.base.BaseFragment;
import com.cloudcc.mobile.view.main.MainUIActivity;
import com.cloudcc.mobile.view.web.CloudWebViewActivity;
import com.cloudcc.mobile.view.web.WebSyncDefaultProxy;
import com.cloudcc.mobile.view.web.WebSyncDefaultProxy.MonitorParam;
import com.cloudcc.mobile.weight.SwipeCalendarView;
import com.cloudcc.mobile.weight.SwipeCalendarView.OnCalendarChangeListener;
import com.cloudcc.mobile.weight.SwipeCalendarView.OnDayItemSelectListener;
import com.cloudcc.mobile.weight.SwipeCalendarView.OnLocationChangeListener;
import com.cloudcc.mobile.weight.SwipeCalendarView.Style;
import com.cloudcc.mobile.widget.CloudCCTitleBar;
import com.cloudcc.mobile.widget.CloudCCTitleBar.OnTitleBarClickListener;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.litesuits.android.log.Log;
import com.mypage.bean.IsWebBean;
import com.mypage.utils.SaveTemporaryData;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * @author wangzhiqiang
 * @Description: 这个页面有可能 是 查看别人的日历 有可能是 查看 自己的日历
 * @date 2015-11-26 下午11:49:23
 */
public class ScheduleMainFragment extends BaseFragment implements
        OnDayItemSelectListener, OnScheduleItemClickListener,
        OnTitleBarClickListener, CreatePopwindow.CreatPop {

    @Bind(R.id.listview)
    ListView mListView;

    @Bind(R.id.tv2)
    LinearLayout tv2;

    @Bind(R.id.schedule_bottom)
    LinearLayout schedule_bottom;

    @Bind(R.id.schedule_date)
    TextView schedule_date;

    @Bind(R.id.no_schedule)
    LinearLayout no_schedule;

    @Bind(R.id.flipper)
    SwipeCalendarView mSwipeCalendarView;

    @Bind(R.id.headerbar)
    CloudCCTitleBar headerbar;

    @Bind(R.id.add_new)
    TextView add_new;
    @Bind(R.id.no_image)
    ImageView no_image;

    @Bind(R.id.addBtnImg)
    ImageView addBtnImg;


    @Bind(R.id.schedule_look_other)
    LinearLayout schedule_look_other;

    @Bind(R.id.quanbushijain)
    TextView quanbushijain;
    @Bind(R.id.layoutFrameClick)
    LinearLayout layoutFrameClick;
    @Bind(R.id.message_num_tz)
    TextView message_num_tz;
    @Bind(R.id.message_num_99)
    TextView message_num_99;

    private SchedulePresenter mSchedulePresenter = new SchedulePresenter();

    private List<ScheduleEntity> mScheduleListData;// 当前日历展示 月份的数据
    String mEns = RunTimeManager.getInstance().getlanguage();
    private String headerTilte = "我的日程";
    private String mAddheader = "的日程";
    private String mTitle = "日程列表";
    private ScheduleListAdapter scheduleAdapter;

    private String belongtoid;// 下属的id
    private List<Date> schedulesArrays;// 2015-01-10
    // 手指按下的点为(x1, y1)手指离开屏幕的点为(x2, y2)
    float x1 = 0;
    float x2 = 0;
    float y1 = 0;
    float y2 = 0;
    Date data;
    // 是否滑动到顶部
    boolean istop;
    public String mClickTime = "";
    public String mClickTimess = "";
    ;
    private CreatePopwindow popwindow;

    @Override
    public void init() {
        EventEngine.register(this);
        popwindow = new CreatePopwindow(getActivity());
        popwindow.setOnCreatPopListener(this);
        //隐藏右点击
//        headerbar.setImage();
        if ("en".equals(mEns)) {
            headerTilte = "Schedules";
            mAddheader = "the schedule";
            mTitle = "Schedule list";
        } else {
            headerTilte = "我的日程";
            mAddheader = "的日程";
            mTitle = "日程列表";
        }
        // Log.d("dangqianshijian",
        // "dangqianshijian" + mSwipeCalendarView.getmSelectDate());
        super.init();
        try {
            Bundle bundle = getArguments();
            tag = bundle.getString("tag", "tg");
        } catch (Exception e) {
            // TODO: handle exception
        }
        initHeader();
        initSwipe();
        requestDatafromCache();
        Log.d("daodizaina", "222");
        requestDataformNet();
        initReceiver();

        // mListView.setOnTouchListener()
        int count = mListView.getCount();
        if (count == 0) {
            no_schedule.setVisibility(View.VISIBLE);
        } else {
            mListView.setVisibility(View.GONE);
        }
        mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem,
                                 int visibleItemCount, int totalItemCount) {
                if (firstVisibleItem == 0) {
                    Log.d("ListView", "##### 滚动到顶部 #####");
                    istop = true;
                } else {
                    istop = false;
                }
            }
        });

        /**
         * 沒有数据
         */
        // no_schedule.setOnTouchListener(new OnTouchListener() {
        // @Override
        // public boolean onTouch(View v, MotionEvent event) {
        // if (event.getAction() == MotionEvent.ACTION_DOWN) {
        // // 当手指按下的时候
        // x1 = event.getX();
        // y1 = event.getY();
        // // Log.d("zuobiao","没有的时候"+ "("+x1+","+y1+")("+x2+","+y2+")");
        // }
        // if (event.getAction() == MotionEvent.ACTION_UP) {
        // // 当手指离开的时候
        // x2 = event.getX();
        // y2 = event.getY();
        // if (y1 - y2 > 50) {
        // mSwipeCalendarView.showWeekUI(data);
        // // Toast.makeText(getActivity(), "向上滑",
        // // Toast.LENGTH_SHORT).show();
        // return true;
        //
        // } else if (y2 - y1 > 50) {
        // mSwipeCalendarView.showMonthUI(data);
        // // Toast.makeText(getActivity(), "向下滑",
        // // Toast.LENGTH_SHORT).show();
        // return true;
        // } else if ((x1 - x2) * (x1 - x2) + (y2 - y1) * (y2 - y1) < 2500) {
        // no_schedule.setOnClickListener(new MyMenuClick(
        // UrlManager.getManager().addReturnUrl(
        // UrlManager.getManager()
        // .getNewTaskOrSchedule(false))));
        // return true;
        // }
        // }
        // return true;
        //
        // }
        // });
    }

    private SyncReceiver mSyncReceiver;

    private void initReceiver() {
        mSyncReceiver = new SyncReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(ReceiverConstant.RECEIVE_REFRESH_SCHEDULE);
        filter.addAction(ReceiverConstant.RECEIVE_REFRESH);
        filter.addAction(ReceiverConstant.RECEIVE_DELETE);
        filter.addAction(ReceiverConstant.RECEIVE_SYNC_WEB);
        mContext.registerReceiver(mSyncReceiver, filter);

        Log.d("daodizaina", "444222");
    }

    private class SyncReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.d("daodizaina", "444" + action);
            requestDataformNet();
        }
    }

    /**
     * 初始化 标题等 intent等
     */
    String tag = "ta";

    private void initHeader() {
        Bundle bundle = getArguments();
        if (bundle != null) {
            belongtoid = bundle.getString(ExtraConstant.EXTRA_ID, "");
            headerTilte = bundle.getString(ExtraConstant.EXTRA_NAME, mTitle);
            headerTilte = headerTilte + mAddheader;

        }
        if (tag.equals("tag")) {
            schedule_look_other.setVisibility(View.GONE);
            layoutFrameClick.setVisibility(View.GONE);
        } else {
            schedule_look_other.setVisibility(View.VISIBLE);
            layoutFrameClick.setVisibility(View.VISIBLE);
        }
        schedule_date.setText(DateUtils.dateToString(new Date(), "yyyy-MM"));
        headerbar.setTitle(headerTilte);
        headerbar.setOnTitleBarClickListener(this);
        Log.d("belongtoid", "belongtoid" + belongtoid);
        if (!TextUtils.isEmpty(belongtoid)) {
//            headerbar.getRightLayout().setVisibility(View.GONE);
            add_new.setVisibility(View.INVISIBLE);
            findViewById(R.id.no_schedule).setEnabled(false);
        }
    }

    /**
     * 获取 日程成功的时候
     *
     * @param event
     */
    public void onEventMainThread(ScheduleListEvent event) {
        headerbar.completeProgress();
        if (event.isError()) {
            return;
        }
        mScheduleListData = event.getData();
        // 当前选择的跟 当前手机上面的日期是同一个月的话 就缓存
        if (com.cloudcc.mobile.util.DateUtils.isSameMonth(
                mSwipeCalendarView.getmSelectDate(), new Date())) {
            CacheManager.getInstance().cacheThisMonthSchedule(
                    CacheManager.IKey.SCHEDULE_MONTH, mScheduleListData);
        }
        refreshScheduleDataOneDay(mSwipeCalendarView.getmSelectDate());
        refreshCalendarAdapter();
    }

    /**
     * 根据日期 从 当前 月份日程数据中获取当前天的日程列表
     *
     * @return
     */
    private List<ScheduleEntity> getschedulesByDay(Date date) {
        /**
         * 逻辑 任务 截至日期 大于等于 当前选择日期 日程 开始日期跟结束日期 之间 包括 当前选择日期的
         * */
        List<ScheduleEntity> schedules = new ArrayList<ScheduleEntity>();
        if (ListUtils.isEmpty(mScheduleListData)) {
            return schedules;
        }
        for (ScheduleEntity schedule : mScheduleListData) {
            if (shoudScheduleInDay(date, schedule)) {
                schedules.add(schedule);
            }
        }
        Collections.sort(schedules);
        return schedules;
    }

    /**
     * 判断一个 日程任务对象 是不是 在 指定的某一天中
     *
     * @param date     日期
     * @param schedule 任务 日程对象
     * @return
     */
    private boolean shoudScheduleInDay(Date date, ScheduleEntity schedule) {
        final Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date);
        if (schedule.isTask()) {// 任务
            Date sdate = schedule.getExpiredateForDate();
            if (sdate != null) {
                final Calendar cals = Calendar.getInstance();
                cals.setTime(sdate);
                return com.cloudcc.mobile.util.DateUtils.isSameDay(cal1, cals);
            }
        } else {// 日程
            Date bdate = schedule.getBegintimeForDate();
            Date edate = schedule.getEndtimeForDate();
            if (bdate == null || edate == null) {
                return false;
            }
            final Calendar calb = Calendar.getInstance();
            calb.setTime(bdate);
            final Calendar cale = Calendar.getInstance();
            cale.setTime(edate);
            if (com.cloudcc.mobile.util.DateUtils.isSameDay(cal1, calb)// 开始时间是跟今天一天
                    || com.cloudcc.mobile.util.DateUtils.isSameDay(cal1, cale)// 结束时间跟今天一天
                    || (calb.before(cal1) && cale.after(cal1)))// 在今天之前开始
            // 在今天之后结束
            {
                return true;
            }

        }
        return false;
    }

    /**
     * 刷新日历 显示当天的日程等
     */
    private void refreshScheduleDataOneDay(Date date) {
        // 刷新当天的
        if (scheduleAdapter == null) {
            scheduleAdapter = new ScheduleListAdapter(mContext);
            scheduleAdapter.setOnScheduleItemClickListener(this);
            mListView.setAdapter(scheduleAdapter);
            mListView.setDivider(new ColorDrawable(0xFFD9D9D9));
            mListView.setDividerHeight(1);
        }
        // 获得当天的数据
        List<ScheduleEntity> list = getschedulesByDay(date);
        no_schedule.setVisibility(ListUtils.isEmpty(list) ? View.VISIBLE
                : View.GONE);
        quanbushijain.setVisibility(ListUtils.isEmpty(list) ? View.GONE
                : View.VISIBLE);
        mListView.setVisibility(ListUtils.isEmpty(list) ? View.GONE
                : View.VISIBLE);
        scheduleAdapter.changeData(list);
        scheduleAdapter.refreshTimeLine();
    }

    @Override
    public void onResume() {
        super.onResume();

        PopuWindowUtils.dissmiss(mRightMenu);
        PopuWindowUtils.setImageView(addBtnImg);
        initHeader();
        MessageSetNCL();
        if (scheduleAdapter != null) {
            scheduleAdapter.refreshTimeLine();
        }
        requestDataformNet();
        // refreshScheduleDataOneDay(mSwipeCalendarView.getmSelectDate());
    }

    private void initSwipe() {
        Log.d("daodizaina", "333");
        mSwipeCalendarView
                .setOnLocationChangeListener(new OnLocationChangeListener() {
                    @Override
                    public void onPrevious(Date date) {
                        // 刷新任务列表
                        if (isThisDayInNowDataMonth(date)) {
                            requestDataformNet();
                        } else {
                            mSwipeCalendarView.mAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onNext(Date date) {
                        if (isThisDayInNowDataMonth(date)) {
                            requestDataformNet();
                        } else {
                            mSwipeCalendarView.mAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onStyleChange(Style style) {
                    }
                });
        mSwipeCalendarView
                .setOnCalendarChangeListener(new OnCalendarChangeListener() {
                    @Override
                    public View getView(int position, View convertView,
                                        Date date) {
                        if (convertView == null) {
                            convertView = LayoutInflater.from(mContext)
                                    .inflate(R.layout.calendar_item, null);
                        }
                        // 点击事件
                        // 判断 当前日期是不是本月的
                        TextView textView = (TextView) convertView
                                .findViewById(R.id.tv1);
                        boolean sameMonth = com.cloudcc.mobile.util.DateUtils
                                .isSameMonth(date,
                                        mSwipeCalendarView.getmCurrentUIDate());
                        textView.setTextColor(sameMonth ? Color.BLACK
                                : Color.GRAY);
                        // 小点
                        TextView ivDot = (TextView) convertView
                                .findViewById(R.id.iv2);
                        boolean hasTaskInToday = hasTaskOrScheduleInDay(date);
                        ivDot.setVisibility(hasTaskInToday ? View.VISIBLE
                                : View.GONE);
                        ImageView ivBackground = (ImageView) convertView
                                .findViewById(R.id.iv1);
                        SimpleDateFormat dateFormat = new SimpleDateFormat("dd");
                        textView.setText(dateFormat.format(date));
                        // Log.d("shijianshezhi",date+"//"+
                        // mSwipeCalendarView.getmSelectDate()+"//"+new
                        // Date()+""+date.equals( new Date()));
                        if (date.equals(mSwipeCalendarView.getmSelectDate())) {
                            ivBackground.setImageResource(R.drawable.circlered);
                            textView.setTextColor(Color.WHITE);
                        } else {
                            ivBackground.setImageDrawable(null);
                        }
                        SimpleDateFormat dateFormat2 = new SimpleDateFormat(
                                "yyyy-MM-dd");
                        String NewTime = dateFormat2.format(new Date());
                        String OldTime = dateFormat2.format(date);
                        Log.d("shijianshezhi", NewTime + ":::" + OldTime
                                + "///" + date.equals(NewTime));
                        try {
                            Date d1 = dateFormat2.parse(NewTime);
                            Date d2 = dateFormat2.parse(OldTime);
                            Log.d("shijbijiao", d1 + "::::" + d2);
                            if (d1.getTime() - d2.getTime() == 0) {
                                ivBackground
                                        .setImageResource(R.drawable.circle);
                                textView.setTextColor(Color.WHITE);
                            }
                        } catch (ParseException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                        return convertView;
                    }

                    @Override
                    public void onNotifyDataChanged() {
                    }
                });
        mSwipeCalendarView.setOnDayItemSelectListener(this);
    }

    /**
     * 判断 当前日期是不是有 任务
     *
     * @param date
     * @return
     */
    private boolean hasTaskOrScheduleInDay(Date date) {
        if (schedulesArrays == null) {
            return false;
        }
        for (Date d : schedulesArrays) {
            if (com.cloudcc.mobile.util.DateUtils.isSameDay(d, date)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void OnItemSelected(int pos, Date date) {
        mClickTime = DateUtils.dateToString(date, "yyyy-MM-dd");
        mClickTimess = DateUtils.dateToString(date, "yyyy-MM-dd HH:mm:ss");
        // 刷新任务 日程列表 换算到 当前选择时间的
        refreshScheduleDataOneDay(date);
    }

    public Date mCurrentShowDate;

    @OnClick(R.id.schedule_today)
    public void clickToday() {
        mSwipeCalendarView.SelectData(new Date());
        // mCurrentShowDate = mSwipeCalendarView.getmCurrentUIDate();
        // mSwipeCalendarView.showWeekUI(mCurrentShowDate);
        mSwipeCalendarView.setmCurrentUIDate(new Date());
        mSwipeCalendarView.showMonthUI(mSwipeCalendarView.getmSelectDate());
        schedule_date.setText(DateUtils.dateToString(new Date(), "yyyy-MM"));
        // requestDataformNet1();
        refreshScheduleDataOneDay(mSwipeCalendarView.getmSelectDate());
        requestDataformNet();
    }

    @OnClick(R.id.schedule_look_other)
    public void clickLookOther() {
        Intent intent = new Intent(mContext, SubStaffListActivity.class);
        startActivity(intent);
        // getActivity().finish();
    }

    private PopupWindow mRightMenu;

    private class MyMenuClick implements OnClickListener {

        private String url = "";

        public MyMenuClick(String url) {
            super();
            this.url = url;
        }

        // 新建
        @Override
        public void onClick(View v) {
            Log.d("dianjiwebview", "web点击" + url);
            PopuWindowUtils.dissmiss(mRightMenu);
            MonitorParam monitorParam = new MonitorParam(
                    new String[]{"m=save"}, WebSyncDefaultProxy.STEP_START,
                    new String[]{"m=query"}, true,
                    WebSyncDefaultProxy.STEP_OVERRIDEURL);
            Intent intent = new Intent(mContext, CloudWebViewActivity.class);
            intent.putExtra(
                    "callback",
                    WebSyncDefaultProxy
                            .creatDefaultProxy(
                                    ReceiverConstant.RECEIVE_REFRESH_SCHEDULE)
                            .addMonitorParam(monitorParam).addHomeMonitor());
            intent.putExtra(ExtraConstant.EXTRA_URL, url);
            startActivity(intent);
        }
    }

    ;

    /**
     * 根据 text提示 判断 是不是 切换月份 需要请求服务器了
     *
     * @param date
     * @return 如果 true 需要请求 如果false 就不用请求服务器
     */
    private boolean isThisDayInNowDataMonth(Date date) {
        // Date schedule_date.setText(DateUtils.dateToString(date,"yyyy年MM月"));
        // 上一个月份
        String lastMonth = schedule_date.getText().toString().trim();
        // 上一个月
        String lastMonthNum = StringUtils.substring(lastMonth, 5, 7);
        // 当前选择的ui月份
        String nowUIMonth = DateUtils.dateToString(date, "yyyy-MM");
        String monthNum = StringUtils.substring(nowUIMonth, 5, 7);
        schedule_date.setText(nowUIMonth);
        return !StringUtils.equals(lastMonthNum, monthNum);
    }

    @Override
    public void OnItemClickHeader(int pos, ScheduleEntity t) {
        // 显示 dialog
        createWainting();
        final String iid = t.id;
        mSchedulePresenter.completeTask(t.id, new RequestListener() {

            @Override
            public void onSuccess(Object arg0) {
                dismissWainting();
                Log.d("fanhuishijian", "fanhuishijian");
                refreshCompleteData(iid);
            }

            @Override
            public void onFailure(ErrorInfo arg0) {
                dismissWainting();
                // 关闭
                Toast.makeText(mContext, arg0.getErrorMessage(), 0).show();
            }
        });
    }

    @Override
    public void onItemScheduleClick(int pos, ScheduleEntity t) {

        Log.d("buzhou", "点击了日程下面的列表");
        SaveTemporaryData.isEventAndTask = true;
        Intent intent = new Intent(mContext, BeauInfoActivity.class);
        intent.putExtra("web", t.id);
        if ((t.id.startsWith("bef")) || ((t.id.startsWith("bfa")))) {
            intent.putExtra("web.url",
                    UrlManager.getRootUrl() + UrlTools.getObjectUrl_z(t.id));
        } else {
            intent.putExtra("web.url",
                    UrlManager.getRootUrl() + UrlTools.getObjectUrl(t.id));
        }
        if (t.isTask()) {
            intent.putExtra("beau.imageid", "cloudtab4");//任务图标
        } else {
            intent.putExtra("beau.imageid", "cloudtabtask");//事件图标
        }

        startActivity(intent);
    }

    /**
     * 刷新完成任务
     *
     * @param id
     */
    private void refreshCompleteData(String id) {
        removefromScheduleList(id);
        Log.d("fanhuishijian", "fanhuishijian11");
        refreshScheduleDataOneDay(mSwipeCalendarView.getmSelectDate());
    }

    /**
     * 从全部的任务中删除一个 任务 根据id
     *
     * @param id
     */
    private void removefromScheduleList(String id) {
        if (ListUtils.isEmpty(mScheduleListData)) {
            return;
        }
        int pos = -1;
        for (int i = 0; i < mScheduleListData.size(); i++) {
            ScheduleEntity item = mScheduleListData.get(i);
            if (StringUtils.equalsIgnoreCase(item.id, id)) {
                pos = i;
                break;
            }
        }
        if (pos != -1) {
            mScheduleListData.remove(pos);
        }
    }

    private void refreshCalendarAdapter() {
        refreshTaskUI();
        if (mSwipeCalendarView.mAdapter != null) {
            mSwipeCalendarView.mAdapter.notifyDataSetChanged();
        }

    }

    private void refreshTaskUI() {
        schedulesArrays = new ArrayList<Date>();
        schedulesArrays.clear();

        // 当前月份的所有任务
        if (ListUtils.isEmpty(mScheduleListData)) {
            return;
        }
        // 日历当前展示月份的数据
        Date[] dateOfMonth = DateUtils.getDateOfMonth(mSwipeCalendarView
                .getmCurrentUIDate());
        for (int i = 0; i < dateOfMonth.length; i++) {
            if (!ListUtils.isEmpty(getschedulesByDay(dateOfMonth[i]))) {
                schedulesArrays.add(dateOfMonth[i]);
            }
        }
    }

    /**
     * 从缓存中获取 当月数据
     */
    private void requestDatafromCache() {
        mScheduleListData = CacheManager.getInstance()
                .getThisMonthScheduleByCache(CacheManager.IKey.SCHEDULE_MONTH);
        refreshScheduleDataOneDay(mSwipeCalendarView.getmSelectDate());
        refreshCalendarAdapter();
    }

    /**
     * 请求网络数据
     */
    public void requestDataformNet() {
        headerbar.beginProgress();
        mSchedulePresenter.getScheduleList(belongtoid,
                mSwipeCalendarView.getmCurrentUIDate());
    }

    /**
     * 请求网络数据
     */
    public void requestDataformNet1() {
        headerbar.beginProgress();
        mSchedulePresenter.getScheduleList(belongtoid, new Date());
    }

    @Override
    public int getLayoutId() {
        return R.layout.schedule_main;
    }


    @Override
    public void onDestroy() {
        EventEngine.uregister(this);
        super.onDestroy();
    }


    @Override
    public void onClickLeft(View v) {
        getActivity().finish();
    }

    @Override
    public void onClickRight(View v) {
//		showRightNew();
        EventEngine.post(new MenuToggleEventR(false, false));
    }

    @OnClick(R.id.add_new)
    public void clickNew() {
        setAddEvent();
    }

    @OnClick(R.id.layoutFrameClick)
    public void clickNews() {
        NearByUtil.startPropertyAnim45(addBtnImg);
        showRightNew();
    }

    @Override
    public void creatOne() {
        String s = "sj";
        NearByUtil.startPropertyAnim00(addBtnImg);
        setCreteHttp(s);
        PopuWindowUtils.dissmiss(mRightMenu);
    }

    @Override
    public void creatTow() {
        String r = "rw";
        NearByUtil.startPropertyAnim00(addBtnImg);
        setCreteHttp(r);
        PopuWindowUtils.dissmiss(mRightMenu);
    }

    @Override
    public void ondismiss() {
        NearByUtil.startPropertyAnim00(addBtnImg);
    }

    private void showRightNew() {

        String sj = "新建事件";
        String rw = "新建任务";
        if ("en".equals(mEns)) {
            sj = "New Event";
            rw = "New Task";
        } else {
            sj = "新建事件";
            rw = "新建任务";
        }

        WindowManager wm = getActivity().getWindowManager();

        int hight = wm.getDefaultDisplay().getHeight() - schedule_bottom.getHeight();
        popwindow.showPopupWindow(tv2, (int) (schedule_bottom.getWidth() - SystemUtils.dpToPx(295,getActivity())), hight);
        popwindow.setImageAndText(R.drawable.new_task_sh, R.drawable.new_task_rw, sj, rw);

    }

    private boolean showTag = true;

    public void onEventMainThread(isshow issh) {
        data = mSwipeCalendarView.getmCurrentUIDate();
        if (issh.isshow) {
            if (showTag) {
                mSwipeCalendarView.showWeekUI(data);
                showTag = !showTag;
            }

        }
        if (!issh.isshow && istop) {
            if (!showTag) {
                Log.d("showmonth", "szdszzzzzz" + data);
                mSwipeCalendarView.showMonthUI(data);
                showTag = !showTag;
            }


        }

    }

    public void setCreteHttp(final String str) {

        HttpUtils utils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addBodyParameter("binding", RunTimeManager.getInstance()
                .getServerBinding());
        params.addBodyParameter("serviceName", "checkIsApp");
        Log.d("判断原生和H5的 url-------------------------", UrlManager.getInterfaceUrl()
                + "?binding=" + RunTimeManager.getInstance().getServerBinding()
                + "&serviceName=getSelectValue");
        utils.send(HttpMethod.POST, UrlManager.getInterfaceUrl(), params,
                new RequestCallBack<String>() {

                    @Override
                    public void onFailure(HttpException arg0, String arg1) {

                        Log.d("H5 ? 接口失败-------------------------", arg1);
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> arg0) {

                        Log.d("H5 ? 接口成功-------------------------", arg0.result);
                        IsWebBean mDdata = new Gson().fromJson(arg0.result, IsWebBean.class);
                        boolean mBool = mDdata.data.istask;
                        if (mBool) {
                            if ("sj".equals(str)) {
                                setIntentEvent();
                            } else {
                                setIntentTask();
                            }

                        } else {
                            if ("sj".equals(str)) {
                                setWebEvent();
                            } else {
                                setWebTask();
                            }

                        }
                    }

                });

    }

    public void setWebEvent() {
        String url = UrlManager
                .getManager().addReturnUrl(
                        UrlManager.getManager().getNewTaskOrSchedule(
                                false,
                                mSwipeCalendarView.getmSelectDate()));
        newEvery(url);
    }

    public void newEvery(String url) {
        MonitorParam monitorParam = new MonitorParam(
                new String[]{"m=save"}, WebSyncDefaultProxy.STEP_START,
                new String[]{"m=query"}, true,
                WebSyncDefaultProxy.STEP_OVERRIDEURL);
        Intent intent = new Intent(mContext, CloudWebViewActivity.class);
        intent.putExtra(
                "callback",
                WebSyncDefaultProxy
                        .creatDefaultProxy(
                                ReceiverConstant.RECEIVE_REFRESH_SCHEDULE)
                        .addMonitorParam(monitorParam).addHomeMonitor());
        intent.putExtra(ExtraConstant.EXTRA_URL, url);
        startActivity(intent);
    }

    public void setWebTask() {
//		new MyMenuClick(UrlManager
//				.getManager().addReturnUrl(
//						UrlManager.getManager().getNewTaskOrSchedule(
//								true,
//								mSwipeCalendarView.getmSelectDate())));

        String url = UrlManager
                .getManager().addReturnUrl(
                        UrlManager.getManager().getNewTaskOrSchedule(
                                true,
                                mSwipeCalendarView.getmSelectDate()));
        newEvery(url);

    }

    @Override
    public LayoutInflater getLayoutInflater(Bundle savedInstanceState) {
        return super.getLayoutInflater(savedInstanceState);
    }

    public void setIntentEvent() {
        Intent intent = new Intent(getActivity(),
                NewEventActivity.class);
        intent.putExtra("clickTime", mClickTimess);
        startActivity(intent);
    }

    public void setIntentTask() {
        Intent intent = new Intent(getActivity(),
                NewTaskActivity.class);
        intent.putExtra("clickTime", mClickTime);
        startActivity(intent);
    }

    public void setAddEvent() {
        HttpUtils utils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addBodyParameter("binding", RunTimeManager.getInstance()
                .getServerBinding());
        params.addBodyParameter("serviceName", "checkIsApp");
        Log.d("判断原生和H5的 url-------------------------", UrlManager.getInterfaceUrl()
                + "?binding=" + RunTimeManager.getInstance().getServerBinding()
                + "&serviceName=getSelectValue");
        utils.send(HttpMethod.POST, UrlManager.getInterfaceUrl(), params,
                new RequestCallBack<String>() {

                    @Override
                    public void onFailure(HttpException arg0, String arg1) {

                        Log.d("H5 ? 接口失败-------------------------", arg1);
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> arg0) {

                        Log.d("H5 ? 接口成功-------------------------", arg0.result);
                        IsWebBean mDdata = new Gson().fromJson(arg0.result, IsWebBean.class);
                        boolean Bool = mDdata.data.istask;
                        if (Bool) {
                            setIntentEvent();
                        } else {
                            setWebEvent();
                        }
                    }

                });


    }
    public void onEventMainThread(MessageNumX event) {

        message_num_tz.setText(event.messageNumX+"");
        if(event.messageNumX>0) {
            message_num_tz.setVisibility(View.VISIBLE);
            if(event.messageNumX>99) {
                message_num_tz.setVisibility(View.INVISIBLE);
                message_num_99.setVisibility(View.VISIBLE);
            }

        }else {
            message_num_tz.setVisibility(View.INVISIBLE);
            message_num_99.setVisibility(View.INVISIBLE);
        }

    }
    private void MessageSetNCL(){
        long messagenum = 0;
        messagenum= RunTimeManager.getInstance().getMessageNx();
        message_num_tz.setText(messagenum+"");

        if(messagenum>0) {
            message_num_tz.setVisibility(View.VISIBLE);
            if(messagenum>99) {
                message_num_tz.setVisibility(View.INVISIBLE);
                message_num_99.setVisibility(View.VISIBLE);
            }

        }else {
            message_num_tz.setVisibility(View.INVISIBLE);
            message_num_99.setVisibility(View.INVISIBLE);
        }

    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
        lp.alpha = bgAlpha;
        getActivity().getWindow().setAttributes(lp);
    }
}
